﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;

namespace THO7AlgoritmTimerApplication
{
    class VisionAlgorithm_MedianL : VisionAlgorithm
    {

        public VisionAlgorithm_MedianL(String name) : base(name) { }

        public unsafe override System.Drawing.Bitmap DoAlgorithm(System.Drawing.Bitmap sourceImage)
        {
            Bitmap outputImage = new Bitmap(sourceImage.Width, sourceImage.Height);

            BitmapData bData = sourceImage.LockBits(new Rectangle(new Point(), sourceImage.Size),
                ImageLockMode.ReadWrite,
                //PixelFormat.Format32bppArgb);   //met alpha channel
                PixelFormat.Format24bppRgb); // zonder alpha channel

            BitmapData bData2 = outputImage.LockBits(new Rectangle(new Point(), sourceImage.Size),
               ImageLockMode.ReadWrite,
                //PixelFormat.Format32bppArgb);   //met alpha channel
               PixelFormat.Format24bppRgb); // zonder alpha channel

            int byteCount = bData.Stride * sourceImage.Height;
            byte[] bmpBytes = new byte[byteCount];
            Marshal.Copy(bData.Scan0, bmpBytes, 0, byteCount);
            //(y * bitmapData.Stride) + x * 3;
            int startPos = (1 * bData.Stride) + 1 * 3;
            byte* pointer = (byte*)((void*)bData.Scan0);
            byte* pointer2 = (byte*)((void*)bData2.Scan0);
            for (int j = startPos; j < bmpBytes.Length - startPos; j ++)
            {
                // int i = 0;
                int[] arr = new int[9];


                arr[0] = pointer[j - bData.Stride - 3];
                arr[1] = pointer[j - bData.Stride];
                arr[2] = pointer[j - bData.Stride + 3];
                arr[3] = pointer[j - 3];
                arr[4] = pointer[j];
                arr[5] = pointer[j + 3];
                arr[6] = pointer[j + bData.Stride - 3];
                arr[7] = pointer[j + bData.Stride];
                arr[8] = pointer[j + bData.Stride + 3];


                QuickSort sort = new QuickSort(arr);
                sort.sortArray();
                arr = sort.Array;

                byte median = (byte)arr[4];
                pointer2[j] = median;
               // pointer2[j + 1] = median;
               // pointer2[j + 2] = median;
            }

            sourceImage.UnlockBits(bData);
            outputImage.UnlockBits(bData2);
            return outputImage;
        }


        private int getMedian(int[] arr)
        {

            QuickSort mySort = new QuickSort(arr);
            mySort.sortArray();
            return mySort.Array[4];
        }
    }
}
